package com.ruoyi.erp.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.erp.domain.*;
import com.ruoyi.erp.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.erp.controller.LedyFeeCheckinController.initAccvouch;
import static com.ruoyi.erp.controller.LedyFeeCheckinController.insertUser;

/**
 * 代支管理Controller
 *
 * @author ztj
 * @date 2023-04-04
 */
@RestController
@RequestMapping("/erp/pay")
public class LedyOuterFeePayController extends BaseController {
    @Autowired
    private ILedyOuterFeePayService ledyOuterFeePayService;
    @Autowired
    private IGlAccvouchService glAccvouchService;
    @Autowired
    private ILedyBacFeeConfigService configService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IGlCashtableService cashtableService;

    @Log(title = "凭证生成", businessType = BusinessType.IMPORT)
    @GetMapping("/sync/{ids}/{type}")
    public AjaxResult faSync(@PathVariable Long[] ids, @PathVariable String type, LedyOuterFeeCollect ledyOuterFeeCollect) {
        List<LedyOuterFeePay> checkins = ledyOuterFeePayService.selectLedyOuterFeePayByIds(ids);
        GlAccvouch accvouch = new GlAccvouch();
        GlAccvouch accvouchQuery = new GlAccvouch();
        List<LedyBacFeeConfig> confList = initAccvouch(ledyOuterFeeCollect.getDbillDate(), "outerFeePay", glAccvouchService, configService, type, accvouch, accvouchQuery);
        final int[] i = {0};
        checkins.forEach(item -> {
            insertUser(i, glAccvouchService, customerService, type, accvouch, accvouchQuery, item.getAcceptNumber(), item.getPayers());
            String cusId = accvouch.getCcusId();
            confList.forEach(conf -> {
                i[0]++;
                if (!conf.getAuxiliaryTerm().contains("ccusId")) {
                    accvouch.setCcusId(null);
                } else {
                    accvouch.setCcusId(cusId);
                }
                accvouch.setInid(Long.parseLong(i[0] + ""));
                accvouch.setCcode(conf.getCcode());
                accvouch.setMd("0");
                accvouch.setMc("0");
                if (conf.getAmount().contains(item.getOuterFeeTypeName().contains("鉴定费") ? "0"
                        : item.getOuterFeeTypeName().contains("差旅费") ? "1" : "2"))
                    if (conf.getRecordCate().equals("借")) {
                        accvouch.setMd(item.getAmount().toString());
                    } else {
                        accvouch.setMc(item.getAmount().toString());
                    }

                if (new BigDecimal(accvouch.getMc()).compareTo(new BigDecimal(0)) <= 0 && new BigDecimal(accvouch.getMd()).compareTo(new BigDecimal(0)) <= 0) {
                    i[0]--;
                    return;
                }
                if (conf.getAmount().contains("amount")) {
                    accvouch.setCdigest("代收收取" + item.getAcceptNumber() + item.getPayers());
                } else {
                    accvouch.setCdigest("代收支出" + item.getAcceptNumber() + item.getPayers());
                }
                accvouch.setCcodeEqual(confList.stream().map(s -> {
                    if (s.getAmount().contains(item.getOuterFeeTypeName().contains("鉴定费") ? "0"
                            : item.getOuterFeeTypeName().contains("差旅费") ? "1" : "2"))
                        if (!s.getCcode().equals(conf.getCcode()) && !s.getRecordCate().equals(conf.getRecordCate())) {
                            if (item.getAmount().compareTo(new BigDecimal(0)) <= 0) {
                                return null;
                            }
                            return s.getCcode();
                        } else return null;
                    else return null;
                }).distinct().collect(Collectors.joining(",")).replaceAll("null,", "").replace(",null", ""));
                accvouch.setCcodeexchEqual(accvouch.getCcodeEqual());
                glAccvouchService.insertGlAccvouch(accvouch);
                if (StringUtil.isNotEmpty(conf.getCashDesc())) {
                    GlCashtable cashtable = new GlCashtable();
                    BeanUtil.copyProperties(accvouch, cashtable);
                    cashtable.setcCashItem(conf.getCashDesc());
                    cashtableService.insertGlCashtable(cashtable);
                }
            });
            LedyOuterFeePay feeCollect = new LedyOuterFeePay();
            feeCollect.setId(item.getId());
            feeCollect.setiNoId(accvouch.getInoId().toString());
            feeCollect.setIflag(1);
            feeCollect.setDbillDate(accvouch.getDbillDate());
            ledyOuterFeePayService.updateLedyOuterFeePay(feeCollect);
        });

        return toAjax(1);
    }

    /**
     * 查询代支管理列表
     */
    @PreAuthorize("@ss.hasPermi('erp:pay:list')")
    @GetMapping("/list")
    public TableDataInfo list(LedyOuterFeePay ledyOuterFeePay) {
        startPage();
        List<LedyOuterFeePay> list = ledyOuterFeePayService.selectLedyOuterFeePayList(ledyOuterFeePay);
        return getDataTable(list);
    }

    /**
     * 导出代支管理列表
     */
    @PreAuthorize("@ss.hasPermi('erp:pay:export')")
    @Log(title = "代支管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LedyOuterFeePay ledyOuterFeePay) {
        List<LedyOuterFeePay> list = ledyOuterFeePayService.selectLedyOuterFeePayList(ledyOuterFeePay);
        ExcelUtil<LedyOuterFeePay> util = new ExcelUtil<LedyOuterFeePay>(LedyOuterFeePay.class);
        util.exportExcel(response, list, "代支管理数据");
    }

    /**
     * 获取代支管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('erp:pay:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ledyOuterFeePayService.selectLedyOuterFeePayById(id));
    }

    /**
     * 新增代支管理
     */
    @PreAuthorize("@ss.hasPermi('erp:pay:add')")
    @Log(title = "代支管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LedyOuterFeePay ledyOuterFeePay) {
        return toAjax(ledyOuterFeePayService.insertLedyOuterFeePay(ledyOuterFeePay));
    }

    /**
     * 修改代支管理
     */
    @PreAuthorize("@ss.hasPermi('erp:pay:edit')")
    @Log(title = "代支管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LedyOuterFeePay ledyOuterFeePay) {
        return toAjax(ledyOuterFeePayService.updateLedyOuterFeePay(ledyOuterFeePay));
    }

    /**
     * 删除代支管理
     */
    @PreAuthorize("@ss.hasPermi('erp:pay:remove')")
    @Log(title = "代支管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ledyOuterFeePayService.deleteLedyOuterFeePayByIds(ids));
    }
}
